#include <sys/types.h>
#include <sys/ipc.h>
#include <sys/shm.h>
#include <sys/stat.h>
#include <sys/fcntl.h>
#include "log.hpp"

const int mem_size = 1024;
const char* tok_file_name = "/home/shr/code/2023_y";
const char* FIFONAME = "file.fifo";
const int proj_id = 0x666;

Log log(MULTIFILE);

class shared_mem
{
public:
    int shmid_get() //获取shmid
    {
        return getShmidHelper(IPC_CREAT);
    }

    int shm_creat() //创建shmid
    {
        return getShmidHelper(IPC_CREAT | IPC_EXCL | 0666);
    }

private:
    int getKey()
    {
        key_t key = ftok(tok_file_name, proj_id);
        if(key < 0) {
            log(FATAL, "%s:%d:getKey err", __FILE__, __LINE__);
            exit(1);
        }
        log(LOG, "getKey done:%d", key);
        return key;
    }

    int getShmidHelper(int flag)
    {
        //以指定方式新建或拿取shmid
        int shmid = shmget(getKey(), mem_size, flag);
        if(shmid < 0) {
            log(FATAL, "%s:%d:shmget err", __FILE__, __LINE__);
            exit(1);
        }
        return shmid;
    }
};

class FIFO
{
public:
    FIFO(const char* fifoName = FIFONAME)
        :_fifo_name(fifoName)
    {
        int ret = mkfifo(fifoName, 0666);
        if(ret < 0) { log(FATAL, "FIFO:mkfifo err"); exit(1); }
        log(LOG, "FIFO mked");
    }

    const char* getFifoName()
    {
        return _fifo_name;
    }

    ~FIFO()
    {
        unlink(_fifo_name);
        log(LOG, "FIFO closed");
    }

private:
    const char* _fifo_name = FIFONAME;
};